package com.openingedu.mba.util;

import java.sql.SQLException;
import java.util.List;

import com.openingedu.mba.persist.DataHelper;
import com.openingedu.mba.persist.PersonalSettings;

import android.content.Context;
import android.util.Log;

public class SettingsUtil {

	private static final String TAG = SettingsUtil.class.getSimpleName();

	/**
	 * 保存设置
	 * @param key
	 * @param value
	 * @param context
	 */
	public synchronized static void persist(String key, String value, Context context) {
		try {
			DataHelper dataHelper = new DataHelper(context);
			PersonalSettings setting = null;
			List<PersonalSettings> settings = dataHelper.getPersonalSettingsDao().queryForEq("key", key);
			if (settings!=null && settings.size() > 0) {
				setting = settings.get(0);
				setting.setKey(key);
				setting.setValue(value);
				dataHelper.getPersonalSettingsDao().update(setting);
				Log.i(TAG, "update settings. setting=" + setting);
			}
			else {
				setting = new PersonalSettings();
				setting.setKey(key);
				setting.setValue(value);
				dataHelper.getPersonalSettingsDao().create(setting);
				Log.i(TAG, "persist settings. setting=" + setting);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 保存设置
	 * @param key
	 * @param value
	 * @param context
	 */
	public synchronized static void persist(String key, boolean value, Context context) {
		persist(key, String.valueOf(value), context);
	}
	
	/**
	 * 取得字符串类型设置
	 * @param key
	 * @param def
	 * @param context
	 * @return
	 */
	public static String queryString(String key, String def, Context context) {
		try {
			DataHelper dataHelper = new DataHelper(context);
			PersonalSettings setting = null;
			List<PersonalSettings> settings = dataHelper.getPersonalSettingsDao().queryForEq("key", key);
			if (settings!=null && settings.size() > 0) {
				setting = settings.get(0);
				Log.i(TAG, "query settings. setting=" + setting);
				return setting.getValue();
			}
			else {
				Log.i(TAG, "key not found. return default. def=" + def);
				return def;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			Log.i(TAG, "query settings error. return default. def=" + def);
			return def;
		}
	}
	
	/**
	 * 取得Boolean类型设置
	 * @param key
	 * @param def
	 * @param context
	 * @return
	 */
	public static boolean queryBoolean(String key, boolean def, Context context) {
		String value = queryString(key, String.valueOf(def), context);
		return Boolean.parseBoolean(value);
	}
}
